package edu.gyc.hishiro.shiro;

import edu.gyc.hishiro.model.SysPermission;
import edu.gyc.hishiro.model.SysRole;
import edu.gyc.hishiro.model.UserInfo;
import edu.gyc.hishiro.service.UserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

@Slf4j
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserInfoService userInfoService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("权限配置-->MyShiroRealm.doGetAuthorizationInfo()");
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        UserInfo userInfo = (UserInfo) principalCollection.getPrimaryPrincipal();
        if (userInfo.getRoles() == null) {
           //新注册的用户没有权限
            throw new UnauthorizedException();
        }
        for (SysRole role : userInfo.getRoles()) {
            authorizationInfo.addRole(role.getRole());

        }
        for (SysPermission p : userInfo.getPermissions()) {
            authorizationInfo.addStringPermission(p.getPermission());
        }
        log.error(authorizationInfo.getRoles() + " permission:" + authorizationInfo.getStringPermissions());
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("开始身份认证");
        String name = (String) token.getPrincipal();

        UserInfo userInfo = userInfoService.findByUsername(name);
        if (userInfo == null) {
            return null;
        }
        //非加密
//        SimpleAuthenticationInfo simpleAuthenticationInfo=new SimpleAuthenticationInfo(
//           myuser.getUsername(),
//                myuser.getPassword(),
//                getName()
//        );

        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
                userInfo,
                userInfo.getPassword(),
                ByteSource.Util.bytes(userInfo.getSalt()),
                getName()
        );
        return simpleAuthenticationInfo;
    }

}

